package com.sc.nft.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sc.nft.dao.*;
import com.sc.nft.entity.*;
import com.sc.nft.entity.dto.SpecialEventManagementEditDTO;
import com.sc.nft.entity.dto.SpecialEventManagementPageDTO;
import com.sc.nft.entity.dto.SpecialEventManagementSaveDTO;
import com.sc.nft.entity.vo.OriginalCopyrightCollectionVO;
import com.sc.nft.entity.vo.OriginalCopyrightSellVO;
import com.sc.nft.entity.vo.OriginalCopyrightVO;
import com.sc.nft.entity.vo.SpecialEventManagementPageVO;
import com.sc.nft.enums.CommodityType;
import com.sc.nft.enums.MarketTypeEnum;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.service.SpecialEventManagementService;
import com.sc.nft.sup.PageRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 专场管理(SpecialEventManagement)表服务实现类
 *
 * @author 王伟成
 * @since 2023-10-10 15:24:31
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SpecialEventManagementServiceImpl implements SpecialEventManagementService {

    private final SpecialEventManagementDao specialEventManagementDao;
    private final SpecialEventManagementBindingDao specialEventManagementBindingDao;
    private final DigitalCollectionProductInfoDao digitalCollectionProductInfoDao;
    private final SecondCollectionDao secondCollectionDao;
    private final DigitalCollectionDao digitalCollectionDao;
    private final SecondCollectionConfigDao secondCollectionConfigDao;
    private final ProductStockDao productStockDao;
    @Override
    public void save(SpecialEventManagementSaveDTO specialEventManagementSaveDTO) {
        SpecialEventManagement specialEventManagement = BeanUtil.copyProperties(specialEventManagementSaveDTO, SpecialEventManagement.class);
        specialEventManagement.setRanking(specialEventManagementSaveDTO.getRank());
        specialEventManagement.setStatus(Boolean.FALSE);
        specialEventManagementDao.save(specialEventManagement);
    }
    @Override
    public void edit(SpecialEventManagementEditDTO specialEventManagementEditDTO) {
        if (!specialEventManagementEditDTO.authentication()) {
            throw new GlobalRunTimeException("参数错误,不可以任何内容未修改进行提交");
        }
        SpecialEventManagement specialEventManagement = BeanUtil.copyProperties(specialEventManagementEditDTO, SpecialEventManagement.class);
        specialEventManagement.setRanking(specialEventManagementEditDTO.getRank());
        specialEventManagement.setId(specialEventManagementEditDTO.getId());
        specialEventManagementDao.updateById(specialEventManagement);
    }
    @Override
    public IPage<SpecialEventManagementPageVO> page(SpecialEventManagementPageDTO specialEventManagementPageDTO) {
        LambdaQueryWrapper<SpecialEventManagement> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.likeRight(StrUtil.isNotBlank(specialEventManagementPageDTO.getEventTitle()),SpecialEventManagement::getEventTitle,specialEventManagementPageDTO.getEventTitle());
        lambdaQueryWrapper.orderByDesc(SpecialEventManagement::getCreateTime);
        return specialEventManagementDao.page(specialEventManagementPageDTO.toMp(), lambdaQueryWrapper).convert(specialEventManagement -> BeanUtil.copyProperties(specialEventManagement, SpecialEventManagementPageVO.class));
    }
    @Override
    public SpecialEventManagementPageVO getById(Long id) {
        return BeanUtil.copyProperties(specialEventManagementDao.getById(id), SpecialEventManagementPageVO.class);
    }
    @Override
    public void removeById(Long id) {
        specialEventManagementDao.removeById(id);
    }
    @Override
    public IPage<OriginalCopyrightVO> pageOriginal(PageRequest pageRequest) {
        // 需要获取到版权列表,根据列表的排序在获取内部的数据.根据列表所绑定的数据,进行查询
        Page<OriginalCopyrightVO> page = specialEventManagementDao.listOriginal(pageRequest.toMp());
        // 获取对应的藏品id,查询1级和2级市场的数据,把有的显示到前面.进行排序
        page.getRecords().forEach(originalCopyrightVO -> {
            List<OriginalCopyrightCollectionVO>excludeIds=new ArrayList<>();
            // 根据id,获取关联的藏品id,根据藏品id,查询1级和2级市场的数据,把有的显示到前面.进行排序
            List<OriginalCopyrightCollectionVO> originalCopyrightCollectionVOS = specialEventManagementBindingDao.listRelevanceCollection(originalCopyrightVO.getId());
            originalCopyrightCollectionVOS.forEach(originalCopyrightCollectionVO -> {
                // 查看1级和2级,看哪个里面有上架or在售的数据.有的话,把onSale修改为true  标明 是哪里来的来源. 如果都没有的话就是空的.
                // 1级市场
                List<DigitalCollectionProductInfo> digitalCollectionProductInfos = digitalCollectionProductInfoDao.selectByCollectionIdAndCommodityType(originalCopyrightCollectionVO.getCollectionId(), CommodityType.COPYRIGHT_COMMODITY);
                DigitalCollection digitalCollection = digitalCollectionDao.getById(originalCopyrightCollectionVO.getCollectionId());
                if (CollUtil.isEmpty(digitalCollectionProductInfos)) {
                    excludeIds.add(originalCopyrightCollectionVO);
                    originalCopyrightCollectionVO.setOnSale(Boolean.FALSE);
                    return;
                }
                if (BeanUtil.isNotEmpty(digitalCollection)&&CollUtil.isNotEmpty(digitalCollectionProductInfos)) {
                    Integer usableStockCount = productStockDao.getUsableStockCount(digitalCollectionProductInfos.get(0).getId());
                    if (usableStockCount > 0) {
                        originalCopyrightCollectionVO.setOnSale(Boolean.TRUE);
                        originalCopyrightCollectionVO.setType(1);
                        originalCopyrightCollectionVO.setId(digitalCollectionProductInfos.get(0).getId());
                    } else {
                        List<SecondCollection> secondCollections = secondCollectionDao.selectByCollectionIdAndMarketType(originalCopyrightCollectionVO.getCollectionId(), MarketTypeEnum.COPYRIGHT);
                        if (CollUtil.isNotEmpty(secondCollections)) {
                            originalCopyrightCollectionVO.setOnSale(Boolean.TRUE);
                            originalCopyrightCollectionVO.setType(2);
                            originalCopyrightCollectionVO.setId(secondCollections.get(0).getId());
                        }else {
                            originalCopyrightCollectionVO.setOnSale(Boolean.FALSE);
                        }
                    }
                }else {
                    originalCopyrightCollectionVO.setOnSale(Boolean.FALSE);
                    originalCopyrightCollectionVO.setType(0);
                }
                // 判断当前时间是否大于开始时间小于结束时间
                if (BeanUtil.isNotEmpty(originalCopyrightCollectionVO)) {
                    originalCopyrightCollectionVO.setFirstTitle(digitalCollection.getFirstTitle());
                    originalCopyrightCollectionVO.setCreationContent(digitalCollection.getCreationContent());
                    // 判定他是在售,还是未开始(暂未开始是1级的情况下,使用1级的售卖开始时间判定),已抢占 (购买时间结束 藏品未被买走 和 藏品已被他人买走，且用户未挂售)
                    if (originalCopyrightCollectionVO.getType() == 1) {
                        Date beginTime = digitalCollectionProductInfos.get(0).getBeginTime();
                        Date endTime = digitalCollectionProductInfos.get(0).getEndTime();
                        // 判断当前时间是否大于开始时间小于结束时间
                        if (originalCopyrightCollectionVO.getOnSale()) {
                            if (new Date().after(beginTime) && new Date().before(endTime)&&(digitalCollectionProductInfos.get(0).getProductType().equals(1)||digitalCollectionProductInfos.get(0).getProductType().equals(2))) {
                                originalCopyrightCollectionVO.setOnSale(Boolean.TRUE);
                            } else if (new Date().after(endTime)) {
                                originalCopyrightCollectionVO.setOnSale(Boolean.FALSE);
                            } else {
                                originalCopyrightCollectionVO.setOnSale(Boolean.FALSE);
                            }
                        }
                    } else if (originalCopyrightCollectionVO.getType() == 2) {
                        // 自由市场藏品状态判定
                        if (originalCopyrightCollectionVO.getOnSale()) {
                            originalCopyrightCollectionVO.setOnSale(Boolean.TRUE);
                        } else {
                            originalCopyrightCollectionVO.setOnSale(Boolean.FALSE);
                        }
                    }
                }
            });




            originalCopyrightVO.setList(originalCopyrightCollectionVOS);
            // 排序.  根据字段rank越大越靠前且onSale字段为True的 其中onSale优先级最高
            Collections.sort(originalCopyrightCollectionVOS,Comparator
                    .comparing((OriginalCopyrightCollectionVO obj) -> obj.getOnSale() ? 1 : 0) // 根据onSale属性排序
                    .reversed() // 降序排列
                    .thenComparing(OriginalCopyrightCollectionVO::getRank, Comparator.reverseOrder()));
            List<OriginalCopyrightCollectionVO> collect = originalCopyrightVO.getList().stream().filter(originalCopyrightCollectionVO -> !excludeIds.contains(originalCopyrightCollectionVO)).collect(Collectors.toList());
            // 重新赋值
            originalCopyrightVO.setList(collect);
            long count = originalCopyrightCollectionVOS.stream().filter(data -> data.getOnSale()).count();
            originalCopyrightVO.setSum(count);
        });

        return page;
    }
    @Override
    public List<OriginalCopyrightSellVO> originalSell(Long id) {
        List<OriginalCopyrightCollectionVO>excludeIds=new ArrayList<>();
        List<OriginalCopyrightSellVO>list=new ArrayList<>();
        List<OriginalCopyrightCollectionVO> originalCopyrightCollectionVOS = specialEventManagementBindingDao.listRelevanceCollection(id);
        originalCopyrightCollectionVOS.forEach(originalCopyrightCollectionVO -> {
            OriginalCopyrightSellVO originalCopyrightSellVO=new OriginalCopyrightSellVO();
            // 获取当前藏品是否在1级or2级有在售
            List<DigitalCollectionProductInfo> digitalCollectionProductInfos = digitalCollectionProductInfoDao.selectByCollectionIdAndCommodityType(originalCopyrightCollectionVO.getCollectionId(), CommodityType.COPYRIGHT_COMMODITY);
            DigitalCollection digitalCollection = digitalCollectionDao.getById(originalCopyrightCollectionVO.getCollectionId());
            // 没上架的干掉.
            if (CollUtil.isEmpty(digitalCollectionProductInfos)) {
                excludeIds.add(originalCopyrightCollectionVO);
                return;
            }
            if (BeanUtil.isNotEmpty(digitalCollection)&&CollUtil.isNotEmpty(digitalCollectionProductInfos)) {
                Integer usableStockCount = productStockDao.getUsableStockCount(digitalCollectionProductInfos.get(0).getId());
                if (usableStockCount > 0) {
                    originalCopyrightSellVO.setId(digitalCollectionProductInfos.get(0).getId());
                    originalCopyrightSellVO.setOnSale(Boolean.TRUE);
                    originalCopyrightSellVO.setType(1);
                    originalCopyrightSellVO.setStatus(1);
                    originalCopyrightSellVO.setCollectionId(digitalCollection.getId());
                    // 售卖价格
                    originalCopyrightSellVO.setPrice(digitalCollectionProductInfos.get(0).getProductNum());
                } else {
                    List<SecondCollection> secondCollections = secondCollectionDao.selectByCollectionIdAndMarketType(originalCopyrightCollectionVO.getCollectionId(), MarketTypeEnum.COPYRIGHT);
                    if (CollUtil.isNotEmpty(secondCollections)) {
                        originalCopyrightSellVO.setId(secondCollections.get(0).getId());
                        originalCopyrightSellVO.setCollectionId(secondCollections.get(0).getCollectionId());
                        originalCopyrightSellVO.setOnSale(Boolean.TRUE);
                        originalCopyrightSellVO.setStatus(1);
                        // 售卖价格
                        originalCopyrightSellVO.setPrice(secondCollections.get(0).getSalesPrice());
                    }else {
                        originalCopyrightSellVO.setOnSale(Boolean.FALSE);
                        originalCopyrightSellVO.setStatus(3);
                        originalCopyrightSellVO.setId(digitalCollectionProductInfos.get(0).getId());
                    }
                    originalCopyrightSellVO.setType(2);
                }

            }else {
                originalCopyrightSellVO.setOnSale(Boolean.FALSE);
                originalCopyrightSellVO.setType(1);
                originalCopyrightSellVO.setStatus(3);
                originalCopyrightSellVO.setCollectionId(digitalCollection.getId());
            }
            if (BeanUtil.isNotEmpty(originalCopyrightSellVO)) {
                originalCopyrightSellVO.setFirstTitle(digitalCollection.getFirstTitle());
                originalCopyrightSellVO.setCreationContent(digitalCollection.getCreationContent());
                // 判定他是在售,还是未开始(暂未开始是1级的情况下,使用1级的售卖开始时间判定),已抢占 (购买时间结束 藏品未被买走 和 藏品已被他人买走，且用户未挂售)
                if(originalCopyrightSellVO.getType()==1){
                    Date beginTime = digitalCollectionProductInfos.get(0).getBeginTime();
                    Date endTime = digitalCollectionProductInfos.get(0).getEndTime();
                    // 判断当前时间是否大于开始时间小于结束时间,同时要确保他已经上架了.
                    if (originalCopyrightSellVO.getOnSale()) {
                        if (new Date().after(beginTime) && new Date().before(endTime)&&(digitalCollectionProductInfos.get(0).getProductType().equals(1)||digitalCollectionProductInfos.get(0).getProductType().equals(2))) {
                            originalCopyrightSellVO.setStatus(1);
                        }else if (new Date().after(endTime)){
                            originalCopyrightSellVO.setOnSale(Boolean.FALSE);
                            originalCopyrightSellVO.setStatus(3);
                        } else  {
                            originalCopyrightSellVO.setOnSale(Boolean.FALSE);
                            originalCopyrightSellVO.setStatus(2);
                        }
                    }
                    originalCopyrightSellVO.setCollectionId(digitalCollection.getId());
                }else if (originalCopyrightSellVO.getType()==2){
                    SecondCollectionConfig byCollectionId = secondCollectionConfigDao.getByCollectionId(originalCopyrightCollectionVO.getCollectionId());
                    // 自由市场藏品状态判定
                    if (originalCopyrightSellVO.getOnSale()) {
                        originalCopyrightSellVO.setStatus(1);
                    }else {
                        originalCopyrightSellVO.setOnSale(Boolean.FALSE);
                        originalCopyrightSellVO.setStatus(3);
                    }
                    if (BeanUtil.isNotEmpty(byCollectionId)) {
                        originalCopyrightSellVO.setConfigId(byCollectionId.getId());
                    } else {
                        // 虽然是卖掉了.但是没有开2级售卖.所以返回1级.
                        originalCopyrightSellVO.setType(1);
                        originalCopyrightSellVO.setCollectionId(digitalCollection.getId());
                    }
                }
            }
            // rank是为了后面要进行排序使用.
            originalCopyrightSellVO.setRank(originalCopyrightCollectionVO.getRank());
            list.add(originalCopyrightSellVO);
            Collections.sort(list,Comparator
                    .comparing((OriginalCopyrightSellVO obj) -> obj.getOnSale() ? 1 : 0) // 根据onSale属性排序
                    .reversed() // 降序排列
                    .thenComparing(OriginalCopyrightSellVO::getRank, Comparator.reverseOrder()));
        });
        List<OriginalCopyrightSellVO> collect = list.stream().filter(originalCopyrightCollectionVO -> !excludeIds.contains(originalCopyrightCollectionVO)).collect(Collectors.toList());
        return collect;
    }
    @Override
    public void unmount(Long id) {
        SpecialEventManagement specialEventManagement = specialEventManagementDao.getById(id);
        if (BeanUtil.isEmpty(specialEventManagement)) {
            throw new GlobalRunTimeException("数据不存在");
        }
        if (specialEventManagement.getStatus()) {
            specialEventManagement.setStatus(Boolean.FALSE);
        }else {
            specialEventManagement.setStatus(Boolean.TRUE);
        }
        specialEventManagementDao.updateById(specialEventManagement);
    }
}
